package com.fastadmin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.http.HttpUtil;
import com.fastadmin.common.exception.EntityExistsException;
import com.fastadmin.config.security.annotation.AnonymousAccess;
import com.fastadmin.mapper.impl.AyiMapper;
import com.fastadmin.mapper.impl.HistoryMapper;
import com.fastadmin.mapper.impl.KeepMapper;
import com.fastadmin.pojo.Ayi;
import com.fastadmin.pojo.FastParam;
import com.fastadmin.pojo.History;
import com.fastadmin.pojo.Keep;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.twelvemonkeys.image.ImageUtil;
import com.xphsc.easyjdbc.page.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FrameFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequiredArgsConstructor
@Slf4j
public class AyiController extends BaseController {

    private final AyiMapper ayiMapper;
    private final KeepMapper keepMapper;
    private final HistoryMapper historyMapper;




    @GetMapping("sys/ayi/index")
    public String index() {
        return "sys/ayi/index";
    }

    @GetMapping("sys/ayi/add")
    public String add() {
        return "sys/ayi/add";
    }

    @GetMapping("sys/ayi/edit")
    public String index(@RequestParam Long ids, Model model) {
        Ayi ayi = this.ayiMapper.findById(ids);
        model.addAttribute("ayi", ayi);
        return "sys/ayi/edit";
    }

    @RequestMapping("sys/ayi/data")
    @ResponseBody
    public Object data(FastParam fastParam) {
        PageInfo<Ayi> pageInfo = this.ayiMapper.findByFastParam(fastParam);
        return datagrid(pageInfo);
    }

    @RequestMapping("sys/ayi/del")
    @ResponseBody
    public Object del(String ids) {
        String[] split = StrUtil.split(ids, ",");
        for (String s : split) {
            ayiMapper.deleteById(s);
        }
        return ok();
    }

    @RequestMapping("sys/ayi/save")
    @ResponseBody
    public Object save(Ayi ayi) {
        if (ObjectUtil.isNotNull(ayi.getId())) {
            //修改
            ayiMapper.update(ayi);
        } else {
            //保存
            ayiMapper.save(ayi);
        }
        return ok();
    }


    @RequestMapping("f/ayi/data")
    @ResponseBody
    @AnonymousAccess
    public Object fdata(int Step ,int EndPos, String openid) {
        HashMap<String, Object> resultMap = Maps.newHashMap();
        FastParam fastParam = new FastParam();
        fastParam.setLimit(Step);
        fastParam.setOffset(EndPos);
        PageInfo<Ayi> pageInfo = this.ayiMapper.findByFastParam(fastParam);
        for (Ayi ayi : pageInfo.getList()) {
            ayi.setNo(ayi.getId() + "");
        }

        resultMap.put("result_code", "ok");
        resultMap.put("YSDATA", pageInfo.getList());
        resultMap.put("EndPos", Step+EndPos);
        resultMap.put("HasData", pageInfo.getList().size());
        return resultMap;
    }
    @RequestMapping("f/ayi/history")
    @ResponseBody
    @AnonymousAccess
    public Object history(int Step ,int EndPos, String openid) {
        HashMap<String, Object> resultMap = Maps.newHashMap();
        FastParam fastParam = new FastParam();
        fastParam.setLimit(Step);
        fastParam.setOffset(EndPos);
        PageInfo<Ayi> pageInfo = this.ayiMapper.findHistoryByOpenId(fastParam, openid);
        for (Ayi ayi : pageInfo.getList()) {
            ayi.setNo(ayi.getId() + "");
        }
        resultMap.put("result_code", "ok");
        resultMap.put("YSDATA", pageInfo.getList());
        resultMap.put("EndPos", Step+EndPos);
        resultMap.put("HasData", pageInfo.getList().size());
        return resultMap;
    }

    @RequestMapping("f/ayi/keep1")
    @ResponseBody
    @AnonymousAccess
    public Object keep1(int Step ,int EndPos, String openid) {
        HashMap<String, Object> resultMap = Maps.newHashMap();
        FastParam fastParam = new FastParam();
        fastParam.setLimit(Step);
        fastParam.setOffset(EndPos);
        PageInfo<Ayi> pageInfo = this.ayiMapper.findKeep1ByOpenId(fastParam, openid);
        for (Ayi ayi : pageInfo.getList()) {
            ayi.setNo(ayi.getId() + "");
        }
        resultMap.put("result_code", "ok");
        resultMap.put("YSDATA", pageInfo.getList());
        resultMap.put("EndPos", Step+EndPos);
        resultMap.put("HasData", pageInfo.getList().size());
        return resultMap;
    }

    @RequestMapping("f/ayi/findAyi")
    @ResponseBody
    @AnonymousAccess
    public Object findAyi(Long no, String openid) throws EntityExistsException {
        //记录浏览了
        History history = History.builder().ayi_id(no).openid(openid).build();
        historyMapper.save(history);
        //浏览次数+1
        ayiMapper.updateMiClick(no);
        //查出浏览的人的头像
        List<Map<String, Object>> Rank_headView = ayiMapper.findUserAvatar(no);

        HashMap<String, Object> resultMap = Maps.newHashMap();
        Ayi ayi = this.ayiMapper.findById(no);
        Map<String, Object> ayiMap = BeanUtil.beanToMap(ayi);

        //技能，先瞎搞几个
        ArrayList<Object> skillList = Lists.newArrayList();
        if (StrUtil.isNotEmpty(ayi.getSkill())) {
            String[] split = ayi.getSkill().split(",");
            for (String skill : split) {
                skillList.add(ImmutableMap.of("name", skill));
            }
        }
        //个人展示图片
        ArrayList<Map> picList = Lists.newArrayList();
        if (StrUtil.isNotEmpty(ayi.getImages())) {
            String[] split = ayi.getImages().split(",");
            for (String image : split) {
                picList.add(ImmutableMap.of("Show", image, "click", image));
            }
        }
        //查看是否被收藏
        boolean isKeep = keepMapper.findByOpenidAndAyiId(openid, no);
        ayiMap.put("Shoucang", isKeep);
        ayiMap.put("Rank_headView", Rank_headView);
        ayiMap.put("HeadView", Rank_headView);
        ayiMap.put("SkillShow", skillList);
        ayiMap.put("PicArry", picList);

        resultMap.put("result_code", "ok");
        resultMap.put("AYidata", ayiMap);

        return resultMap;
    }

    @RequestMapping("/f/ayi/qrcode")
    @AnonymousAccess
    public void qrcode(Long no, HttpServletResponse response) {
        Ayi byId = ayiMapper.findById(no);
        String avatar = byId.getTouxiang();
        String distUrl = "/tmp/avatar/" + byId.getId() + ".jpg";
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        //设置响应类型，告知浏览器输出的是图片
        response.setContentType("image/jpeg");
        //设置HttpOnly属性,防止Xss攻击
        response.setHeader("Set-Cookie", "name=value; HttpOnly");
        QrConfig config = new QrConfig(900, 900);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(1);
        // 高纠错级别
        config.setErrorCorrection(ErrorCorrectionLevel.H);
        // 设置前景色，既二维码颜色（青色）
        HttpUtil.downloadFile(avatar, distUrl);
        config.setImg(distUrl);
        config.setRatio(4);
        config.setForeColor(new Color(61, 130, 42).getRGB());
        config.setBackColor(new Color(242,242,242).getRGB());
        BufferedImage bufferedImage = QrCodeUtil.generate(//
                "http://www.baidu.com",
                config );

        try {
            //以JPEG格式向客户端发送
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(bufferedImage, "PNG",os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/f/ayi/handlerSc")
    @AnonymousAccess
    @ResponseBody
    public Object handlerSc(Long no, String openid, Integer state) {
        //先find，如果存在，那么就是取消收藏
        HashMap<Object, Object> resultMap = Maps.newHashMap();
        resultMap.put("result_code", "ok");
        if (state == 0) {
            //取消收藏
            keepMapper.deleteByNoAndOpenIdAndState(no, openid, 1);
            return resultMap;

        }
        Keep keep = Keep.builder().ayi_id(no).openid(openid).type(1).build();
        keepMapper.save(keep);
        return resultMap;

    }
}
